var global_config = {}
cc.log(test)
/**
 * 响应点击的Sprite
 */
var TouchableSprite = cc.Sprite.extend({
    _touchBegan: false,
    _touchEnabled: true,
    ctor: function (image) {
        this._super(image);
        this._touchListener = cc.EventListener.create({
            event: cc.EventListener.TOUCH_ONE_BY_ONE,
            swallowTouches: true,
            onTouchBegan: this.onTouchBegan,
            onTouchMove: this.onTouchMove,
            onTouchEnded: this.onTouchEnded
        });
    },

    onEnter: function () {
        cc.eventManager.addListener(this._touchListener, this);  // 当Sprite加载完后， 注册点击事件（有好几种注册的方式，在这里就不一一介绍了）。
        this._touchEnabled = true;
        this._super();
    },

    onExit: function () {
        cc.eventManager.removeListener(this._touchListener);
        //当Sprite退出后，取消点击事件的注册。
        this._touchEnabled = false;
        this._super();
    },
    touchRect: function () {
        return this.getBoundingBoxToWorld();
    },
    onTouchBegan: function (touch, event) {
        _self = event.getCurrentTarget();
        if (cc.rectContainsPoint(_self.touchRect(), touch.getLocation())) {
            //当点击在 Sprite 范围内时，执行。
            //在这里处理点击事件。
            this._touchBegan = true;
            return true; //返回true， 才会执行 onTouchEnded方法。
        }
        return false;
    },

    onTouchMove: function(touch, event) {},

    onTouchEnded: function (touch, event) {
        _self = event.getCurrentTarget();
        _self.onTouch && _self.onTouch(touch, event);
        if (this._touchBegan) {
            this._touchBegan = false;
        }
    },
   
    onTouch: function(touch, event) { }
});

var HelloWorldLayer = cc.LayerColor.extend({
    sprite:null,
    ctor:function () {
        //////////////////////////////
        // 1. super init first
        this._super(cc.color(77,83,60,255));

        /////////////////////////////
        // 2. add a menu item with "X" image, which is clicked to quit the program
        //    you may modify it.
        // ask the window size
        var size = cc.winSize;

        // add a "close" icon to exit the progress. it's an autorelease object
        var closeItem = new cc.MenuItemImage(
            res.CloseNormal_png,
            res.CloseSelected_png,
            function () {
                cc.log("Menu is clicked!");
            }, this);
        closeItem.attr({
            x: size.width - 20,
            y: 20,
            anchorX: 0.5,
            anchorY: 0.5
        });
        this.color = new cc.Color(77,83,60);
        var menu = new cc.Menu(closeItem);
        menu.x = 0;
        menu.y = 0;
        this.addChild(menu, 1);

        /////////////////////////////
        // 3. add your codes below...
        // add a label shows "Hello World"
        // create and initialize a label
        var helloLabel = new cc.LabelTTF("Hello World", "FFF Star Condensed2", 38);
        // position the label on the center of the screen
        helloLabel.x = size.width / 2;
        helloLabel.y = 0;
        // add the label as a child to this layer
        this.addChild(helloLabel, 5);

        // add "HelloWorld" splash screen"
        this.sprite = new cc.Sprite(res.end_screen_with_talking);
        this.sprite.attr({
            x: size.width / 2,
            y: size.height / 2,
            scale: 0.5,
            rotation: 180
        });
        this.addChild(this.sprite, 0);

        this.sprite.runAction(
            cc.sequence(
                cc.rotateTo(2, 0),
                cc.scaleTo(2, 1, 1)
            )
        );
        helloLabel.runAction(
            cc.spawn(
                cc.moveBy(2.5, cc.p(0, size.height - 40)),
                cc.tintTo(2.5,255,125,0)
            )
        );
        return true;
    }
});

var SelectLevelLayer = cc.LayerColor.extend({
    sprite: null,
    ctor: function(){
        this._super(cc.color(77,83,60,255));
        var size = cc.winSize;
        this.sprite = new cc.Sprite(res.cart_pipes1);

        this.sprite.getTexture().setAliasTexParameters();
        this.sprite.attr({
            x: size.width / 2,
            y: size.height / 2 + 95,
        });
        this.sprite.setFlippedX(true);
        this.sprite.scale = global_config.scale;
        this.addChild(this.sprite);


        // Add Chip
        var chip = new cc.Sprite(res.inside_cart);
        chip.attr({x: this.sprite.width/2, y: this.sprite.height/2+48, flippedX: true});
        chip.getTexture().setAliasTexParameters();
        var playButton = this.createButton(
            res.play_chip_button, res.play_chip_button_rollover,
            function(){
                var playScene = new goby.GameScene();
                var transition = new cc.TransitionFade(1, playScene, cc.color(77, 84, 60, 255));
                cc.director.runScene(transition);
            },
            chip.width/2,
            chip.height/2-15);

        var exitButton = this.createButton(
            res.new_exit_button, res.new_exit_button_rollover,
            function(){
                var scene = new WelcomeScene();
                var transition = new cc.TransitionFade(1, scene, cc.color(77, 84, 60, 255));
                cc.director.runScene(transition);
            },
            chip.width/2,
            chip.height/2+29);

        var leftButton = this.createButton(
            res.left_button, res.left_button_rollover,
            function(){ cc.log('left clicked!');},
            (chip.width+exitButton.width)/2+16,
            chip.height/2+29);

        var rightButton = this.createButton(
            res.right_button, res.right_button_rollover,
            function(){ cc.log('right clicked!');},
            (chip.width-exitButton.width)/2-16,
            chip.height/2+29);

        var menu = new cc.Menu(playButton, exitButton, leftButton, rightButton);
        menu.x = 0;
        menu.y = 0;
        chip.addChild(menu, 0);

        this.sprite.addChild(chip);

        // Add Sweet Dream
        var sweetDream = new TouchableSprite(res.pack1);
        sweetDream.attr({
            x: this.sprite.width / 2,
            y: this.sprite.height / 2 + 50,
            flippedX: true,
        });
        sweetDream.getTexture().setAliasTexParameters();

        sweetDream.onTouch = function(){
            var move = new cc.MoveTo(1,sweetDream.x, -sweetDream.height );
           sweetDream.runAction(move);
        };

        this.sprite.addChild(sweetDream);

        return true;
    },
    createButton: function(normal,selected, callback, x, y){
        // create item
        var item = new cc.MenuItemImage(normal, selected, callback, this);
        item.attr({x:x, y, rotationY:180});
        var normalImage = item.normalImage;
        var selectedImage = item.selectedImage;
        normalImage && normalImage.texture.setAliasTexParameters();
        selectedImage && selectedImage.texture.setAliasTexParameters();
        selectedImage && (selectedImage.y += normalImage.height - selectedImage.height);

        return item;
    },
});

var StartLayer = cc.LayerColor.extend({
    sprite:null,
    ctor: function(){
        var size = cc.winSize;
        this._super(cc.color(77, 84, 60, 255));
        this.sprite = new cc.Sprite(res.titlescreen0);
        this.sprite.getTexture().setAliasTexParameters();
        this.sprite.attr({
            x: size.width / 2,
            y: size.height / 2,
        });
        cc.log("what is body?" + this.setPhyWorld);
        // Set Title Screen Animation
        var animateSprite = new cc.Sprite(res.titlescreen0);
        animateSprite.attr({
           x: this.sprite.width / 2,
           y: this.sprite.height / 2,
           flippedX: true,
        });
        this.sprite.addChild(animateSprite);

        var animation = this.createAnimation([res.titlescreen0, res.titlescreen1], this.sprite.getSize());
        animation.setDelayPerUnit(1);
        animation.setRestoreOriginalFrame(true);
        var action = cc.animate(animation);
        animateSprite.runAction(cc.repeatForever(action));

        var startButton = new cc.MenuItemImage(
            res.start,res.dove_shadow,
            function(){
                var scene = new SelectScene();
                var transition = new cc.TransitionFade(1, scene, cc.color(77, 84, 60, 255));
                cc.director.runScene(transition);
            }, this);
        startButton.getNormalImage().getTexture().setAliasTexParameters();
        startButton.attr({
            x: this.sprite.width / 2,
            y: this.sprite.height - 52 - startButton.height,
            rotationY: 180,
        });
        var menu = new cc.Menu(startButton);
        menu.x = 0;
        menu.y = 0;
        this.sprite.addChild(menu, 0);

        this.sprite.setFlippedX(true);
        this.sprite.scale = -size.height/this.sprite.height;
        global_config.scale = this.sprite.scale;
        global_config.width = this.sprite.width;
        this.addChild(this.sprite);

        return true;
    },
    createAnimation: function(frames, size){
        var animation = new cc.Animation();
        if (frames instanceof Array) {
            for (var keyRes in frames) {
                var frame = new cc.SpriteFrame(keyRes, cc.rect(0,0,size.width,size.height));
                frame.texture.setAliasTexParameters();
                animation.addSpriteFrame(frame);
            }
        }
        return animation;
    }
});

var WelcomeScene = cc.Scene.extend({
    onEnter:function () {
        this._super();
        cc.log(new goby.GameScene());
        var layer = new StartLayer();
        this.addChild(layer);
    }
});

var SelectScene = cc.Scene.extend({
    onEnter: function() {
        this._super();
        var layer = new SelectLevelLayer();
        this.addChild(layer);
    }
});

